package cc.eddic.pratice.programmingparadigms.emp01array.impl;

import cc.eddic.pratice.programmingparadigms.Employee;
import cc.eddic.pratice.programmingparadigms.Result;
import cc.eddic.pratice.programmingparadigms.emp01array.EmployeeStatisticsService;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.function.Function;

/**
 * 曾奕哲实现的版本
 */
public class StatisticsZyzImpl extends ReaderGcsImpl implements EmployeeStatisticsService {

    @Override
    public Result[] pivotByGender(Employee[] employees) {

        int numMale = 0, numFemale = 0;
        for (Employee e : employees) {
            if (e.getGender().equals("男")) {
                numMale++;
            }
            else numFemale++;
        }

        Result[] results = new Result[] {
                new Result( "男", numMale),
                new Result("女", numFemale)
        };
        Arrays.sort(results, Comparator.comparing(Result::getCount).reversed());

        return results;
    }

    @Override
    public Result[] pivotByDepartment(Employee[] employees) {
        String[] values = new String[employees.length];
        for (int i = 0; i < values.length; i++) {
            values[i] = employees[i].getDepartment();
        }
        return countBy(values);
    }

    @Override
    public Result[] pivotByJobTitle(Employee[] employees) {
        String[] values = new String[employees.length];
        for (int i = 0; i < values.length; i++) {
            values[i] = employees[i].getJobTitle();
        }
        return countBy(values);
    }

    private Result[] countBy(String[] values) {

        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (String value : values) {
            if ( map.containsKey(value) ) {
                map.put(value, map.get(value) + 1);
            }
            else {
                map.put(value, 1);
            }
        }

        int numJobTitle = map.size();
        Result[] results = new Result[numJobTitle];
        int index = 0;
        for (String key : map.keySet()) {
            results[index] = new Result(key, map.get(key));
            index++;
        }
        Arrays.sort(results, Comparator.comparing(Result::getCount).reversed());

        return results;
    }



}
